package org.jpro.modules.system.service.impl;

import java.util.List;

import org.jpro.modules.system.dao.UserRoleRepository;
import org.jpro.modules.system.entity.Role;
import org.jpro.modules.system.entity.User;
import org.jpro.modules.system.entity.UserRole;
import org.jpro.modules.system.service.IUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <P>功能描述 : 用户角色service实现 </P>
 * <P>File name : UserRoleServiceImpl </P>
 * <P>Author : 王泽浩 </P>
 * <P>E-Mail : 1028625100@qq.com </P>
 * <P>Date : 2017/3/4 上午12:04</P>
 */
@Service
@Transactional(readOnly = true)
public class UserRoleServiceImpl implements IUserRoleService {

    @Autowired
    private UserRoleRepository userRoleRepository;

    @Override
    public List<Integer> getRoleIdList(Integer id) {
        return userRoleRepository.fingByUserId(id);
    }

    /**
     * 添加修改用户角色
     * @param userId
     * @param oldRoleIds
     * @param newRoleIds
     */
    @Transactional
    public void updateUserRole(Integer userId, List<Integer> oldRoleIds, List<Integer> newRoleIds) {
        // 是否删除
        for (int i = 0, j = oldRoleIds.size(); i < j; i++) {
            if (!newRoleIds.contains(oldRoleIds.get(i))) {
                userRoleRepository.deleteUR(userId, oldRoleIds.get(i));
            }
        }

        // 是否添加
        for (int m = 0, n = newRoleIds.size(); m < n; m++) {
            if (!oldRoleIds.contains(newRoleIds.get(m))) {
                userRoleRepository.save(getUserRole(userId, newRoleIds.get(m)));
            }
        }
    }

    /**
     * 构建UserRole
     * @param userId
     * @param roleId
     * @return UserRole
     */
    private UserRole getUserRole(Integer userId, Integer roleId) {
        UserRole userRole = new UserRole();
        userRole.setUser(new User(userId));
        userRole.setRole(new Role(roleId));
        return userRole;
    }
}
